package top.ddandang.blog.controller;


import top.ddandang.blog.bean.GlobalResponse;
import top.ddandang.blog.enums.JournalState;
import top.ddandang.blog.model.pojo.Article;
import top.ddandang.blog.model.query.PageBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import top.ddandang.blog.model.vo.*;
import top.ddandang.blog.service.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author D
 * @since 2020-06-23
 */
@RestController
@RequestMapping("/article")
@Slf4j
public class ArticleController {

    @Resource
    private ArticleService articleService;

    @Resource
    private ArticleTagsService articleTagsService;

    @Resource
    private JournalService journalService;

    @Resource
    private CategoriesService categoriesService;

    @Resource
    private StatisticsService statisticsService;

    @Resource
    private TagsService tagsService;

    @PostMapping("/insertArticle")
    public GlobalResponse insertArticle (@RequestBody ArticleVo articleVo) {
        log.info(articleVo.toString());
        //文章文章， 返回文章Id
        int articleId = articleService.insertArticle(articleVo.getTitle(), articleVo.getContentHtml(),
                articleVo.getContentMd(), articleVo.getCategoryId(), articleVo.getDescription(), articleVo.getAllowComment());
        //增加标签 异步处理
        articleTagsService.insertArticleTags(articleVo.getTagsId(), articleId);
        //增加日志 异步处理
        journalService.insertJournal(articleVo.getTitle(), JournalState.NORMAL.getValue(), JournalState.NORMAL.getState());
        //增加分类中文章的数量 异步处理
        categoriesService.updateArticleAmount(articleVo.getCategoryId(), true);
        //增加标签中文章的数量 异步处理
        tagsService.updateArticleAmount(articleVo.getTagsId(), true);
        //增加文章的统计 异步处理
        statisticsService.insertStatistics(articleId);
        return GlobalResponse.success().message("增加成功").data("articleId", articleId);
    }

    @PostMapping("/updateArticle")
    public GlobalResponse updateArticle (@RequestBody ArticleVo articleVo) {
        int flag = articleService.updateArticle(articleVo);
        if(flag == 1) {
            return GlobalResponse.success().message("增加成功");
        }else {
            return GlobalResponse.failed().message("增加失败");
        }

    }

    @PostMapping("/insertImage")
    public GlobalResponse insertImage(MultipartFile file) {

        String url = articleService.insertImage(file);
        return GlobalResponse.success().data("url", url);
    }

    @GetMapping("/listIndexVo")
    public GlobalResponse listIndexVo(@RequestParam(required = true) int pageNo,
                                      @RequestParam(required = true) int pageSize,
                                      @RequestParam(required = false, defaultValue = "0") Integer categoryId,
                                      @RequestParam(required = false, defaultValue = "0") Integer tagsId) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> resultMap = new HashMap<>();
        PageBean pageBean = new PageBean(pageNo, pageSize, 0);
        if(categoryId !=0 && tagsId == 0) {
            map.put("categoryId", categoryId);
        }else if(categoryId ==0 && tagsId != 0) {
            map.put("tagsId", tagsId);
            resultMap = articleService.listArticleMapByTags(pageBean, tagsId);
            return GlobalResponse.success().data(resultMap);
        }
        resultMap = articleService.listIndexVo(pageBean, map);
        return GlobalResponse.success().data(resultMap);
    }

    @GetMapping("/listIndexVoByTitle")
    public GlobalResponse listIndexVoByTitle(@RequestParam(required = true) String title) {
        return GlobalResponse.success().data("listIndexVo", articleService.listIndexVoByTitle(title));
    }

    @GetMapping("/listClassificationVoByCategoryId")
    public GlobalResponse listClassificationVoByCategoryId(Integer categoryId) {
        return GlobalResponse.success().data("listClassification", articleService.listClassificationVoByCategoryId(categoryId));
    }

    @GetMapping("/listClassificationVoByTagsId")
    public GlobalResponse listClassificationVoByTagsId(Integer tagsId) {
        return GlobalResponse.success().data("listClassification", articleService.listClassificationVoByTagsId(tagsId));
    }

    @PostMapping("/removeArticleCategory")
    public GlobalResponse removeArticleCategory(Integer articleId, Integer categoryId) {
        int flag = articleService.removeArticleCategory(articleId);
        if(flag == 1) {
            //减少分类中文章的数量 异步处理
            categoriesService.updateArticleAmount(categoryId, false);
            return GlobalResponse.success();
        }else {
            return GlobalResponse.failed();
        }

    }

    /**
     * 获取文章中分类为空的的文章列表
     * @return 文章列表
     */
    @GetMapping("/listArticleCategoryIsNull")
    public GlobalResponse listArticleCategoryIsNull() {
        return GlobalResponse.success().data("articleList", articleService.listArticleCategoryIsNull());
    }

    /**
     * 批量给未分类的文章增加分类和标签
     * @param sortRequestVo 接受参数封装的类
     * @return 增加状态
     */
    @PostMapping("/addArticleCategoryAndTags")
    public GlobalResponse addArticleCategoryAndTags(@RequestBody SortRequestVo sortRequestVo) {

        //增加文章分类
        articleService.addArticleCategory(sortRequestVo.getCategoryId(), sortRequestVo.getArticleId());
        Map<Integer, Integer> map = articleTagsService.addArticleTags(sortRequestVo.getArticleId(), sortRequestVo.getTagsId());
        //异步批量增加标签数量
        tagsService.addArticleAmount(map);
        return GlobalResponse.success();
    }

    @GetMapping("/getArticleById")
    public GlobalResponse getArticleById(Integer articleId) {
        ArticleDetailVo article = articleService.getArticleById(articleId);
        if(article != null) {
            //增加访问记录（点击量）
            statisticsService.addRedisStatistics(articleId);
            //获取文章的统计数量
            Map<String, Object> map = statisticsService.getStatisticsByArticleId(articleId);
            map.put("article", article);
            return GlobalResponse.success().data(map);
        }else {
            return GlobalResponse.failed().message("获取文章失败！");
        }
    }

    @GetMapping("/listArticleByCategoryId")
    public GlobalResponse listArticleByCategoryId(Integer categoryId) {
        List<Article> articleList = articleService.listArticleByCategoryId(categoryId);
        return GlobalResponse.success().data("articleList", articleList);
    }


    @PostMapping("/listManageVo")
    public GlobalResponse listManageVo(@RequestBody ManageRequestVo manageRequestVo) {
        Map<String, Object> map = new HashMap<>();
        if(manageRequestVo.getCategoryId() != 0) {
            map.put("categoryId", manageRequestVo.getCategoryId());
        }else if (manageRequestVo.getAllowComment() != -1) {
            map.put("allowComment", manageRequestVo.getAllowComment());
        }else if (manageRequestVo.getSort() != -1 && manageRequestVo.getOrder() != -1) {
            map.put("sort", manageRequestVo.getSort());
            map.put("order", manageRequestVo.getOrder());
        }else if (manageRequestVo.getLikeTitle() != null) {
            map.put("title", manageRequestVo.getLikeTitle());
        }
        List<ManageVo> manageVoList = articleService.listManageVo(map);

        if(manageVoList == null || manageVoList.size() == 0) {
            return GlobalResponse.failed();
        }else {
            return GlobalResponse.success().data("manageVoList", manageVoList);
        }
    }

    @PostMapping("/updateArticleAllowComment")
    public GlobalResponse updateArticleAllowComment(Integer articleId, Boolean allowComment) {
        int flag = articleService.updateArticleAllowComment(articleId, allowComment);
        if(flag == 1) {
            return GlobalResponse.success();
        }else {
            return GlobalResponse.failed();
        }
    }

    @PostMapping("/updateArticleTop")
    public GlobalResponse updateArticleTop(Integer articleId, Boolean top) {
        int flag = articleService.updateArticleTop(articleId, top);
        if(flag == 1) {
            return GlobalResponse.success();
        }else {
            return GlobalResponse.failed();
        }
    }

    @DeleteMapping("/deleteArticle")
    public GlobalResponse deleteArticle(Integer articleId) {
        int flag = articleService.deleteArticle(articleId);
        if(flag == 1) {
            return GlobalResponse.success();
        }else {
            return GlobalResponse.failed();
        }
    }

    @GetMapping("/recommendArticles")
    public GlobalResponse recommendArticles() {
        List<Article> articleList = articleService.recommendArticles();
        return GlobalResponse.success().data("articleList", articleList);
    }
}

